package com.dy.树.从前序与中序遍历序列构造二叉树;

import com.dy.树.TreeNode;

/*
 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如，给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树：

    3
   / \
  9  20
    /  \
   15   7
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0 || inorder.length == 0) {
            return null;
        }
        TreeNode root = buildCore(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
        return root;

    }

    //  1           1                      0              0
    private TreeNode buildCore(int[] preorder, int preSt, int preEnd, int[] inorder, int inSt, int inEnd) {

        TreeNode root = new TreeNode(preorder[preSt]);

        int i = inSt;
        for (; i < inEnd + 1; i++) {
            if (inorder[i] == root.val) {

                break;
            }
        }
        int leftLen = i - inSt;
        int rightLen = inEnd - i;
        if (leftLen != 0) {


            TreeNode left = buildCore(preorder, preSt + 1, preSt + leftLen, inorder, inSt, i - 1);
            root.left = left;
        }
        if (rightLen != 0) {
            TreeNode right = buildCore(preorder, preSt + leftLen + 1, preEnd, inorder, i + 1, inEnd);
            root.right = right;
        }

        return root;
    }
}
